package itsm.isperp.module.controller.callcenter;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppConfig;
import itsm.isperp.module.service.app.AppConfigService;
import itsm.isperp.module.service.app.AppUserService;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 控制器
 * 
 * @author lizx
 * @date 2015-01-22 16:25
 */
@Controller
@RequestMapping("callcenter/config")
public class CcConfigController {

	@Autowired
	protected AppConfigService appConfigService;

	@Autowired
	protected AppUserService appUserService;

	@RequestMapping(value = { "", "manage" })
	public ModelAndView manage(HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("callcenter/config");

		List<AppConfig> list = appConfigService.findAll();
		for (AppConfig appConfig : list) {
			mv.addObject(appConfig.getItemKey(), appConfig.getItemValue());
		}
		return mv;
	}

	@RequestMapping(value = { "openEdit" })
	public ModelAndView openEdit(HttpServletRequest req,
			RedirectAttributes redirectAttributes) {
		ModelAndView mv = new ModelAndView();
		String caller = req.getParameter("caller");
		JqGridRequest request = new JqGridRequest();
		request.setSearchString(" a.tel LIKE '%" + caller
				+ "%' OR mobile LIKE '%" + caller + "%'");
		Map<String, Object> u = appUserService.findOneDetailByRequest(request);

		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
		if (u != null) {

			String sql = "SELECT COUNT(*) FROM icd_incident WHERE cus_user_id='"
					+ u.get("id").toString()
					+ "'  AND  create_date > date_sub(now(), interval 2 day); ";
			mv.addObject("cuCount",
					jdbcTemplate.queryForObject(sql, Integer.class));
			mv.setViewName("callcenter/openEdit");
			mv.addObject("cusUser", u);
			mv.addObject("caller", caller);
		} else {
			mv.setViewName("redirect:/incident/incident/newIncidentEdit");
			redirectAttributes.addAttribute("caller", caller);

		}

		return mv;
	}
}
